<?php
class UserForms {

    private static $errorMsg = array();


    public static function registerForm($inputs) {

        echo '<form method="post" action="index.php?action=registerUser">';
        echo '<table id="register">';
        if(isset($inputs['registerButton'])) {

            if(strlen($inputs['username']) == 0) {

                self::$errorMsg['username'] = "Моля въведете потребителско име!";
                echo '<tr><td>Потребителско име:</td><td><input id="username" name="username"/></td></tr><tr><td class="error">'.self::$errorMsg['username'].'</td></tr>';

            } elseif (DBUtils::checkIfUserIsTaken($inputs['username']) == true) {

                self::$errorMsg['username'] = "Това потребителско име вече е заето!";
                echo '<tr><td>Потребителско име:</td><td><input id="username" name="username"/></td></tr><tr><td class="error">'.self::$errorMsg['username'].'</td></tr>';

            } else {

                echo '<tr><td>Потребителско име:</td><td><input id="username" name="username" value="'.$inputs['username'].'"/></td></tr>';

            }

            if(strlen($inputs['email']) == 0) {

                self::$errorMsg['email'] = "Моля въведете e-mail адрес!";
                echo '<tr><td>E-mail:</td><td><input id="email" name="email"/></td></tr><tr><td class="error">'.self::$errorMsg['email'].'</td></tr>';

            } elseif (DBUtils::checkIfEmailIsTaken($inputs['email']) == true){

                self::$errorMsg['email'] = "Този e-mail адрес вече е зает!";
                echo '<tr><td>E-mail:</td><td><input id="email" name="email"/></td></tr><tr><td class="error">'.self::$errorMsg['email'].'</td></tr>';

            }  else if(!filter_var($inputs['email'], FILTER_VALIDATE_EMAIL)) {
            	
            	self::$errorMsg['email'] = "Неправилен формат на e-mail адрес!";
            	echo '<tr><td>E-mail:</td><td><input id="email" name="email"/></td></tr><tr><td class="error">'.self::$errorMsg['email'].'</td></tr>';
            	
            }else {

                echo '<tr><td>E-mail:</td><td><input id="email" name="email" value="'.$inputs['email'].'"/></td></tr>';
            }

            if(strlen($inputs['password']) == 0) {

                self::$errorMsg['password'] = "Моля въведете парола!";
                echo '<tr><td>Парола:</td><td><input type="password" id="password" name="password"/></td></tr><tr><td class="error">'.self::$errorMsg['password'].'</td></tr>';

            } elseif (strlen($inputs['password']) < 6){

                self::$errorMsg['password'] = "Паролата трябва да бъде поне 6 символа!";
                echo '<tr><td>Парола:</td><td><input type="password" id="password" name="password"/></td></tr><tr><td class="error">'.self::$errorMsg['password'].'</td></tr>';

            }  else {

                echo '<tr><td>Парола:</td><td><input type="password" id="password" name="password" value="'.$inputs['password'].'"/></td></tr>';
            }

            if(strlen($inputs['password2']) == 0) {

                self::$errorMsg['password2'] = "Моля повторете вашата парола!";
                echo '<tr><td>Повторете паролата:</td><td><input type="password" id="password2" name="password2"/></td></tr><tr><td class="error">'.self::$errorMsg['password2'].'</td></tr>';

            } elseif ($inputs['password'] != $inputs['password2']){

                self::$errorMsg['password2'] = "Паролите не съвпадат!";
                echo '<tr><td>Повторете паролата:</td><td><input type="password" id="password2" name="password2"/></td></tr><tr><tdclass="error">'.self::$errorMsg['password2'].'</td></tr>';

            }  else {

                echo '<tr><td>Повторете паролата:</td><td><input type="password" id="password2" name="password2" value="'.$inputs['password'].'"/></td></tr>';
            }


            echo '<tr><td><button id="registerButton" name="registerButton" class="button">Регистрирай ме!</button></td></tr>
                </form>
                </table>';

        } else {

            echo '<tr><td>Потребителско име:</td><td><input id="username" name="username"/></td></tr>
                <tr><td>E-mail:</td><td><input id="email" name="email"/></td></tr>
                <tr><td>Парола:</td><td><input type="password" id="password" name="password"/></td></tr>
                <tr><td>Повторете паролата:</td><td><input type="password" id="password2" name="password2"/></td></tr>
                <tr><td><button id="registerButton" name="registerButton" class="button">Регистрирай ме!</button></td></tr>
                </form>
                </table>';
        }

        if (isset($inputs['registerButton']) && empty(self::$errorMsg)) {
            $inputs['username'] = htmlspecialchars($inputs['username']);
            $inputs['email'] = htmlspecialchars($inputs['email']);

            DBUtils::registerUser($inputs);
        }
    }

    public static function loginForm($inputs) {

        echo '<form action="index.php" method="post">';
        echo '<table id="login">					
            <tr><td>Потребителско име:</td></tr>
            <tr><td><input id="userlog" name="userlog"/></td></tr>
            <tr><td>Парола:</td></tr>
            <tr><td><input type="password" id="passlog" name="passlog"/></td></tr>
            <tr><td><button id="loginButton" name="loginButton" class="button">Влез</button></td></tr>
            </table>
            </form>';

        if(isset($inputs['loginButton'])) {

            if(strlen($inputs['userlog']) == 0) {

                self::$errorMsg['error'] = "Невалидни данни!";
            }

            if(strlen($inputs['passlog']) == 0) {

                self::$errorMsg['error'] = "Невалидни данни!";
            }
        }

        if (isset(self::$errorMsg['error'])) {

            echo '<p class="error">'.self::$errorMsg['error'].'</p>';
        }

        if (isset($inputs['loginButton']) && empty(self::$errorMsg)) {

            $inputs['userlog'] = htmlspecialchars($inputs['userlog']);

            $pass = md5($inputs['passlog']);
            $userData = DBUtils::getProfileData($inputs['userlog']);

            if($inputs['userlog'] != $userData['user_name'] || $pass != $userData['password']) {

                self::$errorMsg['error'] = "Невалидни данни!";
                echo '<p class="error">'.self::$errorMsg['error'].'</p>';

            } else {

                Utils::loginUser($userData);
            }
        }
    }

    public static function editForm(Profile $profile, $inputs, $files){

    	$userData = DBUtils::getProfileData($profile->getUsername());
    	
        echo '<form method="post" action="office.php?action=profile_active" enctype= "multipart/form-data">';
        echo '<table>';
        echo '<tr><td>Потребителско име:</td><td>'.$profile->getUsername().'</td></tr>
            <tr><td>E-mail:</td><td>'.$profile->getEmail().'</td></tr>
            <tr><td>Име:</td><td><input id="first_name" name="first_name" value="'.$profile->getFirstName().'" /></td></tr>
            <tr><td>Фамилия:</td><td><input id="last_name" name="last_name" value="'.$profile->getLastName().'" /></td></tr>
            <tr><td>Статус:</td><td><input id="status" name="status" value="'.$profile->getStatus().'" /></td></tr>';

        if(isset($inputs['editButton'])) {
            $directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']); 
            $uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'uploads/'; 
            $uploads_dir = realpath(dirname(__FILE__)).'\uploads';

            if (strlen($files['profile_picture']['name'])){
                if($files['profile_picture']['error'] !== UPLOAD_ERR_OK) {
                    self::$errorMsg['profile_picture'] = "Upload failed with error code " . $_FILES['file']['error'];
                    echo '<tr><td>Снимка:</td><td>
                        <img width="100px" src="uploads/'.$profile->getProfilePic().'" />
                        <input id="picture" type="file" name="profile_picture"/>
                        </td></tr>
                        <tr><td class="error">'.self::$errorMsg['profile_picture'].'</td></tr>';
                }else{
                    $info = getimagesize($files['profile_picture']['tmp_name']);
                    if($info === FALSE){
                        self::$errorMsg['profile_picture'] = "Unable to determine image type of uploaded file";
                        echo '<tr><td>Снимка:</td><td>
                            <img width="100px" src="uploads/'.$profile->getProfilePic().'" />
                            <input id="picture" type="file" name="profile_picture"/>
                            </td></tr>
                            <tr><td class="error">'.self::$errorMsg['profile_picture'].'</td></tr>';
                    }elseif (($info[2] !== IMAGETYPE_GIF) && ($info[2] !== IMAGETYPE_JPEG) && ($info[2] !== IMAGETYPE_PNG)) {
                        self::$errorMsg['profile_picture'] = "This image type is not allowed.";
                        echo '<tr><td>Снимка:</td><td>
                            <img width="100px" src="uploads/'.$profile->getProfilePic().'" />
                            <input id="picture" type="file" name="profile_picture"/>
                            </td></tr>
                            <tr><td class="error">'.self::$errorMsg['profile_picture'].'</td></tr>';
                    }else{
                        move_uploaded_file($files['profile_picture']['tmp_name'], $uploadsDirectory.$files['profile_picture']['name']);
                        echo '<tr><td>Снимка:</td><td>
                            <img width="100px" src="uploads/'.$files['profile_picture']['name'].'" />
                            <input id="picture" type="file" name="profile_picture"/>
                            </td></tr>';
                    }
                }
            }else{
                echo '<tr><td>Снимка:</td><td>
                    <img width="100px" src="uploads/'.$profile->getProfilePic().'" />
                    <input id="picture" type="file" name="profile_picture"/>
                    </td></tr>';
            }

            if(strlen($inputs['old_password']) > 0){
            	
               /* $userData = DBUtils::getProfileData($profile->getUsername()); */
                $old_pass = md5($inputs['old_password']);

                if($old_pass != $userData['password']){
                    self::$errorMsg['old_password'] = "Старата парола е грешна!";
                    echo '<tr><td>Стара Парола:</td><td><input type="password" id="old_password" name="old_password" /></td></tr><tr><td class="error">'.self::$errorMsg['old_password'].'</td></tr>';
                    echo '<tr><td>Нова паролата:</td><td><input type="password" id="password" name="password"/></td></tr>
                        <tr><td>Повторете новата паролата:</td><td><input type="password" id="password2" name="password2"/></td></tr>';
                }else{
                    echo '<tr><td>Стара Парола:</td><td><input type="password" id="old_password" name="old_password"/></td></tr>';
                    if(strlen($inputs['password']) == 0) {
                        self::$errorMsg['password'] = "Моля въведете нова парола!";
                        echo '<tr><td>Нова Парола:</td><td><input type="password" id="password" name="password"/></td></tr><tr><td class="error">'.self::$errorMsg['password'].'</td></tr>';
                    } elseif (strlen($inputs['password']) < 6){
                        self::$errorMsg['password'] = "Паролата трябва да бъде поне 6 символа!";
                        echo '<tr><td>Нова Парола:</td><td><input type="password" id="password" name="password"/></td></tr><tr><td class="error">'.self::$errorMsg['password'].'</td></tr>';
                    }  else {
                        echo '<tr><td>Нова Парола:</td><td><input type="password" id="password" name="password"/></td></tr>';
                    }

                    if(strlen($inputs['password2']) == 0) {
                        self::$errorMsg['password2'] = "Моля повторете вашата парола!";
                        echo '<tr><td>Повторете новата паролата:</td><td><input type="password" id="password2" name="password2"/></td></tr><tr><td class="error">'.self::$errorMsg['password2'].'</td></tr>';
                    } elseif ($inputs['password'] != $inputs['password2']){
                        self::$errorMsg['password2'] = "Паролите не съвпадат!";
                        echo '<tr><td>Повторете новата паролата:</td><td><input type="password" id="password2" name="password2"/></td></tr><tr><td class="error">'.self::$errorMsg['password2'].'</td></tr>';
                    }  else {
                        echo '<tr><td>Повторете новата паролата:</td><td><input type="password" id="password2" name="password2"/></td></tr>';
                    }
                }
            }else{
                echo '<tr><td>Стара Парола:</td><td><input type="password" id="old_password" name="old_password" /></td></tr>
                <tr><td>Нова паролата:</td><td><input type="password" id="password" name="password"/></td></tr>
                <tr><td>Повторете новата паролата:</td><td><input type="password" id="password2" name="password2"/></td></tr>';
            }
        } else {
            echo '<tr><td>Снимка:</td><td>
                <img width="100px" src="uploads/'.$profile->getProfilePic().'" />
                <input id="picture" type="file" name="profile_picture" />
                </td></tr>
                <tr><td>Стара Парола:</td><td><input type="password" id="old_password" name="old_password" /></td></tr>
                <tr><td>Нова паролата:</td><td><input type="password" id="password" name="password"/></td></tr>
                <tr><td>Повторете новата паролата:</td><td><input type="password" id="password2" name="password2"/></td></tr>';
        }
        echo '<tr><td><button id="editButton" name="editButton" class="button">Запази промените</button></td></tr>
            </form>
            </table>';

        if (isset($inputs['editButton']) && empty(self::$errorMsg) && $profile) {
        	
            $inputs['first_name'] = htmlspecialchars($inputs['first_name']);
            $inputs['last_name'] = htmlspecialchars($inputs['last_name']);
            $inputs['status'] = htmlspecialchars($inputs['status']);

            if($files['profile_picture']['name'] != null){
            	
            	$profile->setProfilePic($files['profile_picture']['name']);
                DBUtils::setProfilePic($files['profile_picture']['name'], $profile->getProfileID());
            }
           
            $profile->setFirstName($inputs['first_name']);
            $profile->setLastName($inputs['last_name']);
            $profile->setStatus($inputs['status']);
            DBUtils::updateProfileData($inputs, $profile->getProfileID());
            if(($old_pass == $userData['password']) &&  ($inputs['password'] == $inputs['password2'])) {
            	
            	DBUtils::setPassword($inputs['password'], $profile->getProfileID());
            }

        }
    }
}
